package yagwl.client.widget.internal;

import yagwl.client.resource.Resources;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;

/**
 * Lays out buttons or other actionable widgets, followed by busy indicator and
 * message.
 * <p>
 * <b>CSS styles</b><br>
 * .ya-buttonBar-button - button<br>
 * .ya-buttonBar-message - message<br>
 * .ya-buttonBar-error - error message
 */
public class ButtonBar extends Composite {
  private final FlowPanel rootFlowPanel = new FlowPanel();
  private final Image busyI = new Image(Resources.I.getInlineBusy());
  private final Label messageL = new Label();
  private final ActionTimer timer = new ActionTimer();
  
  public ButtonBar() {
    busyI.setVisible(false);
    initWidget(rootFlowPanel);
  }
  
  public void add(Button button) {
    rootFlowPanel.add(button);
    button.setStyleName("ya-buttonBar-button");
  }

  /**
   * Renders the widget. This must be called for the widget to be rendered.
   */
  public void renderUI() {
    rootFlowPanel.add(busyI);
    rootFlowPanel.add(messageL);
  }

  /**
   * Displays or un-displays busy indicator
   */
  public void setBusy(boolean busy) {
    if (busy) {
      messageL.setText("");
      timer.cancel();
    }
    for (int i = 0; i < rootFlowPanel.getWidgetCount() - 2; i++) {
      if (rootFlowPanel.getWidget(i) instanceof Button) {
        ((Button) rootFlowPanel.getWidget(i)).setEnabled(!busy);
      }
    }
    busyI.setVisible(busy);
  }

  /**
   * Displays message
   * 
   * @param message
   *          message to be displayed
   * @param displaySeconds
   *          seconds for how long message is displayed
   */
  public void setMessage(String message, int displaySeconds) {
    messageL.setStyleName("ya-buttonBar-message");
    setStatus(message, displaySeconds);
  }

  /**
   * Displays error message
   * 
   * @param message
   *          error message to be displayed
   * @param displaySeconds
   *          seconds for how long error message is displayed
   */
  public void setErrorMessage(String message, int displaySeconds) {
    messageL.setStyleName("ya-buttonBar-error");
    setStatus(message, displaySeconds);
  }

  private void setStatus(String message, int displaySeconds) {
    setBusy(false);
    messageL.setText(message);
    if (displaySeconds > 0) {
      timer.cancel();
      timer.schedule(displaySeconds * 1000);
    }
  }

  private class ActionTimer extends Timer {

    @Override
    public void run() {
      messageL.setText("");
    }

  }

}
